package com.iwayin.core;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.Version;

public class LuceneTest {
	private static final File INDEX_DIR = new File("F:/index");  
	private static final Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://127.0.0.1:3306/iwayin";
		String user = "root";               
		String password = "root";
		Connection conn = null;
		try {
			//
			Class.forName(driver);       
			conn = DriverManager.getConnection(url, user, password); 
			if(!conn.isClosed()){
				System.out.println("connect DB successful.");
			}
			PreparedStatement ps = conn.prepareStatement("select * from w_user");
			ResultSet rs = ps.executeQuery();
			IndexWriter writer = openIndexWriter();
			while(rs.next()){
				System.out.println("id "+rs.getLong(1));
				System.out.println("name "+rs.getString(2));
				Document document = builderDocument(rs.getLong(1),rs.getString(2));  
				writer.addDocument(document);  
			}
			writer.close();
			List<String> result = search("name", "xiaobo");
			if(result.size()>0){
				for(String name :result){
					System.out.println(name);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			conn = null;
		}
	}
	
	public static Document builderDocument(Long uid, String name) {
		Document document = new Document();
		Field id = new Field("id", String.valueOf(uid), Field.Store.YES,
				Field.Index.ANALYZED);
		Field firstName = new Field("name", name, Field.Store.YES,
				Field.Index.ANALYZED);
		document.add(id);
		document.add(firstName);
		return document;

	}
	
	public static IndexWriter openIndexWriter() throws CorruptIndexException, LockObtainFailedException, IOException {
		IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_35,
				analyzer);
		iwc.setOpenMode(OpenMode.CREATE);
		return new IndexWriter(FSDirectory.open(INDEX_DIR), iwc);
	}
	
	public static Query buildQuery(String fieldName, String criteria)
			throws ParseException, CorruptIndexException, IOException {
		QueryParser parser = new QueryParser(Version.LUCENE_35, fieldName,
				analyzer);
		return parser.parse(criteria);
	} 
	
	public static List<String> search(String name,String target) throws CorruptIndexException, IOException, ParseException{
		IndexReader reader = IndexReader.open(FSDirectory.open(INDEX_DIR)); 
		IndexSearcher searcher = new IndexSearcher(reader); 
		List<String> list = new ArrayList<String>();
		
		Query query = buildQuery("name","xiaobo");
		TopDocs topDocs = searcher.search(query, 10);
		int total = topDocs.totalHits;
		System.out.println("total=" + total);
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		for (int i = 0; i < scoreDocs.length; i++) {
			Document doc = searcher.doc(scoreDocs[i].doc);
			list.add(doc.get("name"));
		}
		return list;

	}


}
